package admin

import (
	"errors"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"mycms/global"
	"mycms/model/system"
	systemReq "mycms/model/system/request"
	systemRes "mycms/model/system/response"
	"mycms/service/common"
	"mycms/utils"
)

//	后台登录
func Login(u system.Admin) (err error, admin system.Admin) {

	// 否则 附加uuid 密码md5简单加密 注册
	u.Password = utils.MD5V([]byte(u.Password))

	err = global.DB.Where("username = ? AND password = ?", u.Username, u.Password).First(&admin).Error

	return err, admin
}

//	获取用户信息
func GetUserInfo(u global.Model) (err error, admin system.Admin) {
	err = global.DB.Where("id = ?", u.ID).First(&admin).Error
	return err, admin
}

//	获取管理员列表
func GetAdminLists(param systemReq.SearchAdminParams) (err error, list interface{}, total int64) {

	var adminList []system.Admin
	var adminRes []systemRes.AdminListResponse

	db := global.DB.Model(&system.Admin{})
	err = db.Count(&total).Error

	if err != nil {
		return err, adminList, total
	} else {

		//	筛选条件
		if param.Username != "" {
			db = db.Where("username LIKE ?", "%"+param.Username+"%")
		}

		if param.Realname != "" {
			db = db.Where("realname LIKE ?", "%"+param.Realname+"%")
		}

		if param.Phone != "" {
			db = db.Where("realname LIKE ?", "%"+param.Phone+"%")
		}

		if param.Status != 0 {
			db = db.Where("status = ?", param.Status)
		}

		//	查询
		err = db.Scopes(common.Paginate(param.PageInfo)).Find(&adminList).Error

		//	有数据时，循环处理一下数据
		if len(adminList) > 0 {
			for _, v := range adminList {
				var role_name []string
				if v.RoleId != ""{
					_ = global.DB.Model(&system.Role{}).Where("id IN ?", common.StringToInt(v.RoleId, ",")).Select("name").Find(&role_name).Error
				}

				adminRes = append(adminRes, systemRes.AdminListResponse{
					Id:        v.ID,
					Username:  v.Username,
					Status:    v.Status,
					CreatedAt: v.CreatedAt.Format("2006-01-02 15:04:05"),
					Phone:     v.Phone,
					Email:     v.Email,
					Realname:  v.Realname,
					Remark:    v.Remark,
					Avatar:    v.Avatar,
					RolesName: role_name,
				})

			}
		}
	}

	return err, adminRes, total
}

//	编辑管理员
func UpdateAdmin(param systemReq.UpdateAdminParams) (err error) {
	var admin system.Admin
	err = global.DB.Where("id = ?", param.Id).First(&admin).Error

	if err == nil {
		//	更新
		err = global.DB.Model(admin).Updates(&param).Error
	}

	return err

}

//	添加管理员
func CreateAdmin(user system.Admin) (err error) {
	err = global.DB.Where("username = ?", user.Username).First(&user).Error

	// 判断用户名是否注册
	if !errors.Is(err, gorm.ErrRecordNotFound) {
		return errors.New("帐号名已注册")
	}
	// 否则 附加uuid 密码md5简单加密 注册
	user.Password = utils.MD5V([]byte(user.Password))
	user.Uuid = uuid.New() //	生成uid
	err = global.DB.Create(&user).Error
	return err
}

//	删除管理员
func DelAdmin(param systemReq.AdminDelParams) (err error) {
	var admin system.Admin
	err = global.DB.Where("id = ?", param.Id).Delete(&admin).Error
	return err
}
